﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule;
using System.Web.Caching;
using System.Text;

public partial class UserControl_OrgQuery : System.Web.UI.UserControl
{
    private const string ALL_TEXT = "全 部";
    private const string ALL_VALUE = "-1";
    private const string WARNING_1 = "没有组织或业代基础数据";

    /// <summary>
    /// 只读属性：组织结构
    /// </summary>
    public String ParameterOrg
    {
        get
        {
            #region
            //DataSet ds = GetData();
            //if (ds != null && ds.Tables.Count > 1)
            //{
            //    //获取业代信息表
            //    DataTable dt = ds.Tables[1];
            //    DataRow[] rows;
            //    StringBuilder strB = new StringBuilder();
            //    if (SalesRepCodes != "")
            //    {

            //        rows = dt.Select(string.Format("SalesRepNo in ({0})", SalesRepCodes));
            //        //
            //        strB.Append(string.Format("业代({0})：", SalesRepCodes.Replace('\'', ' ')));
            //        foreach (DataRow row in rows)
            //        {
            //            strB.Append(row["SalesRep"]);
            //            strB.Append(" ");
            //        }
            //    }
            //    else if (DirectorCodes != "")
            //    {
            //        rows = dt.Select(string.Format("SalesRepNo in ({0})", DirectorCodes));
            //        strB.Append(string.Format("主任({0})：", DirectorCodes.Replace('\'', ' ')));
            //        foreach (DataRow row in rows)
            //        {
            //            strB.Append(row["SalesRep"]);
            //            strB.Append(" ");
            //        }
            //    }
            //    else if (OrgCodes != "")
            //    {
            //        //获取组织结构信息表
            //        dt = ds.Tables[0];
            //        rows = dt.Select(string.Format("OrgCode in ({0}) and OrgLevel={1}", OrgCodes, Cache["OrgLevel"]));
            //        strB.Append(string.Format("{0}({1})：", Cache["OrgName"], OrgCodes.Replace('\'',' ')));
            //        foreach (DataRow row in rows)
            //        {
            //            strB.Append(row["OrgName"]);
            //            strB.Append(" ");
            //        }
            //    }
            //    else if (SalesRepID != ALL_VALUE)
            //    {
            //        strB.Append(string.Format("业代：{0}", this.DDLSalesRep.SelectedItem.Text));
            //    }
            //    else if (DirectorID != ALL_VALUE)
            //    {
            //        strB.Append(string.Format("主任：{0}", this.DDLDirector.SelectedItem.Text));
            //    }
            //    else if (OrgID != ALL_VALUE)
            //    {
            //        strB.Append(Cache["OrgName"]);
            //    }
            //    else
            //    {
            //        return "全 国";
            //    }
            //    return strB.ToString();
            //}
            #endregion
            return WARNING_1;
        }
    }
    /// <summary>
    /// 用于过滤用户输入的特殊字符
    /// </summary>
    /// <param name="sqlStr"></param>
    /// <returns></returns>
    private string SqlFilter(string sqlStr)
    {
        sqlStr = sqlStr.Replace('，', ',').Replace('\'', ' ').Replace('\"', ' ').TrimEnd(',').TrimStart(',').Trim();
        if (sqlStr.Length > 0)
        {
            //添加单引号 
            return "'" + sqlStr.Replace(",", "','") + "'";
        }
        return "";
    }

    /// <summary>
    ///  只读属性：部门编号
    /// </summary>
    public String OrgCodes
    {
        get
        {
            if (txtSalesOffCodes.Text.Trim() != "")
            {
                Cache["OrgLevel"] = "3";
                Cache["OrgName"] = "营业所";
                return SqlFilter(txtSalesOffCodes.Text);
            }
            else if (txtRegionCodes.Text.Trim() != "")
            {
                Cache["OrgLevel"] = "2";
                Cache["OrgName"] = "区域";
                return SqlFilter(txtRegionCodes.Text);
            }
            else if (txtOUCodes.Text.Trim() != "")
            {
                Cache["OrgLevel"] = "1";
                Cache["OrgName"] = "瓶装厂";
                return SqlFilter(txtOUCodes.Text);
            }
            else
            {
                return "";
            }
        }
    }
    /// <summary>
    /// 只读属性：组织结构等级
    /// </summary>
    public String OrgLevel
    {
        get { return (String)Cache["OrgLevel"]; }
    }
    /// <summary>
    /// 只读属性：部门ID号
    /// </summary>
    public String OrgID
    {
        get
        {
            if (!String.IsNullOrEmpty(OrgCodes))
                return null;
            if (DDLSalesOff.SelectedValue != ALL_VALUE)
            {
                //Cache["OrgName"] = string.Format("营业所：{0}", DDLSalesOff.SelectedItem.Text);
                Cache["OrgLevel"] = "3";
                return DDLSalesOff.SelectedValue;
            }
            else if (DDLRegion.SelectedValue != ALL_VALUE)
            {
                //Cache["OrgName"] = string.Format("区域：{0}", DDLRegion.SelectedItem.Text);
                Cache["OrgLevel"] = "2";
                return DDLRegion.SelectedValue;
            }
            else if (DDLOU.SelectedValue != ALL_VALUE)
            {
                //Cache["OrgName"] = string.Format("瓶装厂：{0}", DDLOU.SelectedItem.Text);
                Cache["OrgLevel"] = "1";
                return DDLOU.SelectedValue;
            }
            else
            {
                return ALL_VALUE;
            }
        }
    }
    /// <summary>
    /// 只读属性：主任编号
    /// </summary>
    public String DirectorCodes
    {
        get { return SqlFilter(this.txtDirectorCodes.Text); }
    }
    /// <summary>
    /// 只读属性：主任ID号
    /// </summary>
    public String DirectorID
    {
        get { return this.DDLDirector.SelectedValue; }
    }
    /// <summary>
    /// 只读属性：业代编号
    /// </summary>
    public String SalesRepCodes
    {
        get { return SqlFilter(this.txtSalesRepCodes.Text); }
    }
    /// <summary>
    /// 只读属性：业代ID号
    /// </summary>
    public String SalesRepID
    {
        get { return this.DDLSalesRep.SelectedValue; }
    }

    decimal _DomainID;
    /// <summary>
    /// 只写属性
    /// </summary>
    public decimal DomainID
    {
        set { this._DomainID = value; }
    }
    decimal _UserOrgLevel;
    /// <summary>
    /// 只写属性(当前用户所属组织结构等级)
    /// </summary>
    public decimal UserOrgLevel
    {
        set { this._UserOrgLevel = value; }
    }
    int _UserOrgID;
    /// <summary>
    /// 只写属性(当前用户所属组织结构等级)
    /// </summary>
    public int UserOrgID
    {
        set { this._UserOrgID = value; }
    }

    /// <summary>
    /// 方法：初始化页面
    /// </summary>
    public void InitMethod(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                DataSet ds = GetData();
                if (ds != null && ds.Tables.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    //绑定OU(瓶装厂)
                    this.DDLOU.DataTextField = "OrgName";
                    this.DDLOU.DataValueField = "OrgID";
                    dt.DefaultView.RowFilter = "OrgLevel=1";
                    this.DDLOU.DataSource = dt.DefaultView;
                    this.DDLOU.DataBind();
                    this.DDLOU.Items.Insert(0, new ListItem(ALL_TEXT, ALL_VALUE));

                    if (this._UserOrgLevel == 1)
                    {
                        this.DDLOU.SelectedValue = this._UserOrgID.ToString();
                        //初始化区域下拉列表
                        DDLOU_SelectedIndexChanged(sender, e);
                        //
                        this.DDLOU.Enabled = false;
                    }
                    else if (this._UserOrgLevel == 2)
                    {
                        this.DDLOU.SelectedValue = dt.Select(string.Format("OrgID={0}", this._UserOrgID))[0]["ParentID"].ToString();
                        //初始化区域下拉列表
                        DDLOU_SelectedIndexChanged(sender, e);
                        this.DDLRegion.SelectedValue = this._UserOrgID.ToString();
                        //初始化营业所下拉列表
                        DDLRegion_SelectedIndexChanged(sender, e);
                        this.DDLOU.Enabled = false;
                        this.DDLRegion.Enabled = false;
                    }
                    else if (this._UserOrgLevel == 3)
                    {
                        string regionID = dt.Select(string.Format("OrgID={0}", this._UserOrgID))[0]["ParentID"].ToString();
                        this.DDLOU.SelectedValue = dt.Select(string.Format("OrgID={0}", regionID))[0]["ParentID"].ToString();
                        //初始化区域下拉列表
                        DDLOU_SelectedIndexChanged(sender, e);
                        this.DDLRegion.SelectedValue = regionID;
                        //初始化营业所下拉列表
                        DDLRegion_SelectedIndexChanged(sender, e);
                        this.DDLSalesOff.SelectedValue = this._UserOrgID.ToString();
                        //初始化主任下拉列表
                        DDLSalesOff_SelectedIndexChanged(sender, e);
                        this.DDLOU.Enabled = false;
                        this.DDLRegion.Enabled = false;
                        this.DDLSalesOff.Enabled = false;
                        
                    }
                }
            }
        }
        catch
        { }
    }

    /// <summary>
    /// 获取部门表
    /// </summary>
    /// <returns></returns>
    private DataSet GetData()
    {
        if (Cache["OrgTable"] == null)
        {
            //从数据库取数据
            DataSet ds = new ReportManager().GetOrganization(this._DomainID);
            //缓存该数据集(滑动到期)
            Cache.Insert("OrgTable", ds, null, System.Web.Caching.Cache.NoAbsoluteExpiration,
                TimeSpan.FromMinutes(20));
        }
        return (DataSet)Cache["OrgTable"];
    }
    /// <summary>
    /// 选择OU
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void DDLOU_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.DDLOU.SelectedValue != "")
        {
            DataSet ds = GetData();
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                //绑定区域
                this.DDLRegion.DataTextField = "OrgName";
                this.DDLRegion.DataValueField = "OrgID";
                dt.DefaultView.RowFilter = string.Format("ParentID={0} and OrgLevel=2", this.DDLOU.SelectedValue);
                this.DDLRegion.DataSource = dt.DefaultView;
                this.DDLRegion.DataBind();
                this.DDLRegion.Items.Insert(0, new ListItem(ALL_TEXT, ALL_VALUE));
                this.DDLSalesOff.Items.Insert(0, new ListItem(ALL_TEXT, ALL_VALUE));
            }
        }
    }
    /// <summary>
    /// 选择区域
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void DDLRegion_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.DDLRegion.SelectedValue != "")
        {
            DataSet ds = GetData();
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                //绑定营业所
                this.DDLSalesOff.DataTextField = "OrgName";
                this.DDLSalesOff.DataValueField = "OrgID";
                dt.DefaultView.RowFilter = string.Format("ParentID={0} and OrgLevel=3", this.DDLRegion.SelectedValue);
                this.DDLSalesOff.DataSource = dt.DefaultView;
                this.DDLSalesOff.DataBind();
                this.DDLSalesOff.Items.Insert(0, new ListItem(ALL_TEXT, ALL_VALUE));
            }
        }
    }
    /// <summary>
    /// 选择营业所
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void DDLSalesOff_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.DDLSalesOff.SelectedValue != "")
        {
            DataSet ds = GetData();
            if (ds != null && ds.Tables.Count > 1)
            {
                DataTable dt = ds.Tables[1];
                //绑定主任
                this.DDLDirector.DataTextField = "SalesRep";
                this.DDLDirector.DataValueField = "UserID";
                DataRow[] rows = dt.Select("ManagerID>0");
                if (rows.Length > 0)
                {
                    StringBuilder str_B = new StringBuilder();
                    foreach (DataRow row in rows)
                    {
                        str_B.Append(row["ManagerID"]);
                        str_B.Append(",");
                    }
                    dt.DefaultView.RowFilter = string.Format("OrgID={0} and UserID in ({1})",
                        this.DDLSalesOff.SelectedValue, str_B.ToString().TrimEnd(','));
                    this.DDLDirector.DataSource = dt.DefaultView;
                    this.DDLDirector.DataBind();
                    this.DDLDirector.Items.Insert(0, new ListItem(ALL_TEXT, ALL_VALUE));
                }


                //初始化该营业所下面的所有业代
                this.DDLSalesRep.DataTextField = "SalesRep";
                this.DDLSalesRep.DataValueField = "UserID";
                dt.DefaultView.RowFilter = string.Format("OrgID={0}", this.DDLSalesOff.SelectedValue);
                this.DDLSalesRep.DataSource = dt.DefaultView;
                this.DDLSalesRep.DataBind();
                this.DDLSalesRep.Items.Insert(0, new ListItem(ALL_TEXT, ALL_VALUE));
            }
        }
    }
    /// <summary>
    /// 选择主任
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void DDLDirector_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.DDLDirector.SelectedValue != "")
        {
            DataSet ds = GetData();
            if (ds != null && ds.Tables.Count > 1)
            {
                DataTable dt = ds.Tables[1];
                //绑定业代
                this.DDLSalesRep.DataTextField = "SalesRep";
                this.DDLSalesRep.DataValueField = "UserID";
                dt.DefaultView.RowFilter = string.Format("ManagerID={0}", this.DDLDirector.SelectedValue);
                this.DDLSalesRep.DataSource = dt.DefaultView;
                this.DDLSalesRep.DataBind();
                this.DDLSalesRep.Items.Insert(0, new ListItem(ALL_TEXT, ALL_VALUE));
            }
        }
    }
}
